﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Hi_Baidu.Cache
{
    /// <summary>
    ///     缓存管理器基类 - 提供了缓存的管理相关操作
    /// </summary>
    public class CacheManager : Manager
    {
        /// <summary>
        ///     缓存管理器基类 - 提供了缓存的管理相关操作
        /// </summary>
        /// <param name="CleanCacheTimer">清除缓存计时器</param>
        /// <param name="Interval">清除间隔</param>
        public CacheManager(System.Timers.Timer CleanCacheTimer, int Interval)
        {
            this.cleanCacheTimer = CleanCacheTimer;
            this.cleanCacheTimer.Interval = Interval;
            this.cleanCacheTimer.Elapsed += new System.Timers.ElapsedEventHandler(cleanCacheTimer_Elapsed);
            this.cleanCacheTimer.Start();
        }

        void cleanCacheTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            DateTime CleanTime = DateTime.Now;
            foreach (IMetaData metaData in this.Collection)
            {
                if ((metaData as Cache.CacheObject.Cache).ExpridTime < CleanTime)
                {
                    (metaData as Cache.CacheObject.Cache).Dispose();
                    break;
                }
            }
        }

        private System.Timers.Timer cleanCacheTimer;
        /// <summary>
        ///    清除缓存计时器
        /// </summary>
        public System.Timers.Timer CleanCacheTimer
        {
            get { return cleanCacheTimer; }
        }

        /// <summary>
        ///     重置该缓存管理器
        /// </summary>
        public void Clear()
        {
            if(this.cleanCacheTimer != null)
            {
                this.cleanCacheTimer.Stop();
                this.Collection.Clear();
            }
        }

        /// <summary>
        ///     丛集合中移除指定KEY对象
        /// </summary>
        /// <param name="Key"></param>
        public void Clear(String Key)
        {
            foreach (IMetaData metaData in this.Collection)
            {
                if ((metaData as Cache.CacheObject.Cache).Key == Key)
                {
                    (metaData as Cache.CacheObject.Cache).Dispose();
                    break;
                }
            }
        }
    }
}
